﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;

namespace KTX
{
    public partial class FrmConfig : Form
    {
        public const string STR_SEC = "Data Source={0};Initial Catalog={1};User Id={2};Password={3};";
        public const string STR_TRU = "Data Source={0};Initial Catalog={1};Integrated Security=SSPI;";

        public FrmConfig()
        {
            InitializeComponent();
        }

        private void radWin_CheckedChanged(object sender, EventArgs e)
        {
            ChangeText(false);
        }

        private void radSql_CheckedChanged(object sender, EventArgs e)
        {
            ChangeText();
        }

        private void ChangeText(bool change = true)
        {
            txtPass.Enabled = change;
            txtUser.Enabled = change;
        }

        private string StrCnn()
        {
            string sver = cbbServer.Text;
            string user = txtUser.Text;
            string pass = txtPass.Text;
            string data = cbbDB.Text;
            string str;

            if (radWin.Checked == true)
                str = String.Format(STR_TRU, sver, (data == "" ? "master" : data));
            else
                str = String.Format(STR_SEC, sver, data, user, pass);

            return str;
        }

        private void cmdOk_Click(object sender, EventArgs e)
        {
            try
            {
                Configuration _config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                _config.ConnectionStrings.ConnectionStrings[1].ConnectionString = StrCnn();
                _config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection(_config.ConnectionStrings.SectionInformation.Name);
                Properties.Settings.Default.Reload();

                MessageBox.Show("Đã lưu cấu hình!" + Environment.NewLine + "Xin hãy khởi động lại chương trình!");

                Close();
                Application.Exit();
            }
            catch (Exception ex)
            {
                string s = String.Format("{0};{1}", "Không tìm thấy file cấu hình!", ex.Message);
                string t = String.Format("{0};{1}", "Lỗi", "Error");
                MessageBox.Show(s, t);
            }
        }
    }
}
